#!/bin/sh

#
# Wrapper script to find python version to use.
#

# Debug message helper
dbg () {
    [ "$DEBUG" -eq 1 ] && echo "$*" >&2
}

# Find suitable python binary
find_py_bin () {
    which -a python | while read -r TRY_PY_BIN
    do
        dbg "Trying python bin: $TRY_PY_BIN"

        PY_VMAJOR=$($TRY_PY_BIN -c "import sys; print(sys.version_info[0])")
        PY_VMINOR=$($TRY_PY_BIN -c "import sys; print(sys.version_info[1])")

        if [ "$PY_VMAJOR" -eq 3 ]; then
            echo "$TRY_PY_BIN"
            exit 0
        elif [ "$PY_VMAJOR" -eq 2 ] && [ "$PY_VMINOR" -gt "6" ]; then
            echo "$TRY_PY_BIN"
            exit 0
        fi
    done
}

# Find path to the real ansible-cmdb python script
find_cmdb_bin () {
    BIN_DIR=$(dirname "$0")
    if [ -f "$BIN_DIR/ansible-cmdb.py" ]; then
        dbg "Trying ansible-cmdb bin: $BIN_DIR/ansible-cmdb.py"
        echo "$BIN_DIR/ansible-cmdb.py"
    elif [ -f "$BIN_DIR/../lib/ansible-cmdb/ansible-cmdb.py" ]; then
        dbg "Trying ansible-cmdb bin: $BIN_DIR/../lib/ansible-cmdb/ansible-cmdb.py"
        echo "$BIN_DIR/../lib/ansible-cmdb/ansible-cmdb.py"
    elif [ -f "$BIN_DIR/../lib/ansiblecmdb/ansible-cmdb.py" ]; then
        dbg "Trying ansible-cmdb bin: $BIN_DIR/../lib/ansiblecmdb/ansible-cmdb.py"
        echo "$BIN_DIR/../lib/ansiblecmdb/ansible-cmdb.py"
    else
        echo "Couldn't find $BIN_DIR/ansible-cmdb.py in . or $BIN_DIR/../lib/ansible-cmdb/ or $BIN_DIR/../lib/ansiblecmdb/ (cwd=$PWD)" >&2
        exit 2
    fi
}

DEBUG=0
if [ "$1" = "-d" ] || [ "$1" = "--debug" ]; then
    DEBUG=1
fi

PY_BIN="$(find_py_bin)"
if [ -z "$PY_BIN" ]; then
    echo "No suitable python version found (v2.7 or higher required). Aborting" >&2
    exit 1
fi

CMDB_BIN="$(find_cmdb_bin)"
if [ -z "$CMDB_BIN" ]; then
    echo "Couldn't find ansible-cmdb.py. Aborting" >&2
    exit 2
fi

# Run it
dbg "Using python bin $PY_BIN"
dbg "Using ansible-cmdb bin $CMDB_BIN"
"$PY_BIN" "$CMDB_BIN" "$@"
